<template>
  <div class="page-content">
    <table-bar
      :showTop="false"
      layout="search,refresh"
      @search="search"
      @reset="resetForm(searchFormRef)"
      @changeColumn="changeColumn"
    >
      <template #top>
        <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
          <el-row :gutter="20">
            <form-input label="用户名" prop="nickname" v-model="searchForm.nickname" />
            <form-input label="手机号" prop="phone" v-model="searchForm.phone" />
            <form-input label="工号" prop="work_number" v-model="searchForm.work_number" />
            <form-input label="所属部门" prop="dept_id" v-model="searchForm.dept_id" />
          </el-row>
          <el-row :gutter="20">
<!--            <form-input label="用户ID" prop="id" v-model="searchForm.id" />-->
<!--            <form-select label="性别" prop="sex" v-model="searchForm.sex" :options="sexOptions" />-->
<!--            <form-select-->
<!--              label="会员等级"-->
<!--              prop="level"-->
<!--              v-model="searchForm.level"-->
<!--              :options="levelOptions"-->
<!--            />-->
          </el-row>
        </el-form>
      </template>
      <template #bottom>
        <el-button @click="showDialog('add')" v-ripple>添加用户</el-button>
      </template>
    </table-bar>

    <art-table :data="subUserList" :total="total">
      <template #default>
        <el-table-column label="用户名" prop="nickname" />
        <el-table-column label="工号" prop="work_number" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="所属部门" prop="dept.name" />
        <el-table-column label="状态" prop="status" #default="scope">
          <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1" @change="changStatus(scope.row,$event)"></el-switch>
        </el-table-column>
        <el-table-column label="创建日期" prop="create_time" sortable />
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <button-table type="edit" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" @click="deleteUser(scope.row)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加账号' : '编辑账号'"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="nickname">
          <el-input v-model="formData.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="工号" prop="work_number">
          <el-input v-model="formData.work_number" />
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-select multiple v-model="formData.role_ids">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="dept_id">
          <el-select v-model="formData.dept_id">
            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import {UserService} from '@/api/user/userApi'
  import {RoleService} from '@/api/user/roleApi'
  import {DeptService} from '@/api/user/deptApi'

  const dialogType = ref('add')
  const dialogVisible = ref(false)

  const formData = reactive({
    nickname: '',
    phone: '',
    work_number: '',
    role_ids: [],
    dept_id: ''
  })

  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    work_number: '',
    phone: '',
    nickname: '',
    create_time:'',
    dept_id: '',
    page:1,
    limit:10
  })

  const roleList = ref([])
  const deptList = ref([])
  const subUserList = ref([])
  const total = ref(0)

  // 获取角色列表
  const getRoleList = async () => {
    const res = await RoleService.getRolePage()
    roleList.value = res.data.list
  }

  // 获取部门列表
  const getDeptList = async () => {
    const res = await DeptService.getDeptList()
    deptList.value = res.data
  }
  // 获取账号列表
  const getSubUserList = async () => {
   const res = await UserService.getSubUserPage(searchForm)
    subUserList.value = res.data.list
    total.value = res.data.total
  }
  getRoleList()
  getDeptList()
  getSubUserList()

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }

  // 账号状态切换
  const changStatus = (row:any,e:any) => {
    console.log(e)
    if(e === 1) {
      UserService.subUserEnable({id:row.id})
    } else {
      UserService.subUserDisable({id:row.id})
    }
  }

  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      formData.nickname = row.nickname
      formData.phone = row.phone
      formData.work_number = row.work_number
      formData.dept_id = row.dept_id
      let role_ids = []
      row.roles.forEach(item => {role_ids.push(item.id)})
      formData.role_ids = role_ids
    } else {
      formData.nickname = ''
      formData.work_number = ''
      formData.phone = ''
      formData.dept_id = ''
      formData.role_ids = []
    }
  }

  const deleteUser = (row:any) => {
    ElMessageBox.confirm('确定要删除该账号吗？', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      await UserService.subUserDelete({id:row.id})
      await getSubUserList()
      ElMessage.success('删除成功')
    })
  }

  const search = () => {}

  const changeColumn = (list: any) => {
    columns.values = list
  }

  const filterTag = (value: string, row: any) => {
    return row.status === value
  }

  const rules = reactive<FormRules>({
    nickname: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    role_ids: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async(valid) => {
      if (valid) {
        if(dialogType.value === 'add') {
          await UserService.subUserCreate(toRaw(formData))
        } else {
          await UserService.subUserUpdate(toRaw(formData))
        }
        await getSubUserList()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;

    .user {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
